import instance from '../../utils/request';

//声明 reducer 函数            2
let todoReducer = (state=[], action) => {
  //
  switch(action.type){
    //初始化设置
    case 'init_todos':
      return action.payload;
    //新增任务
    case 'add_todo':
      return [...state, action.payload];
    //删除任务
    case 'remove_todo':
      return state.filter(item => item.id !== action.payload);
    //更新任务
    case 'check_todo':
      return state.map(item => {
        //判断
        if(item.id === action.payload.id){
          //更新任务的状态
          item.done = action.payload.done;
        }
        return item;
      })
    default: 
      return state;
  }
}

//暴露
export default todoReducer;

//声明一个异步的 action creator
//获取任务列表, 并更新 redux 中的 todo 数据
export let asyncGetTodo = () => {
  return async (dispatch) => {
    //发送请求
    let result = await instance.get('/todos');
    //更新状态
    dispatch({type: 'init_todos', payload: result});
  }
}

//声明异步的 action creator
export let asyncAddTodo = (title) => {
  return async dispatch => {
    //发送 AJAX 请求
    let result = await instance.post('/todos', {
      title: title,
      done: false
    });
    //更新 redux 中的任务列表
    dispatch({type: 'add_todo', payload: result});
  }
}

//删除任务
export let asyncRemoveTodo = (id) => {
  return async dispatch => {
    //发送请求
    await instance.delete(`/todos/${id}`);
    //更新 redux 中的状态
    dispatch({type: "remove_todo", payload: id});
  }
}

//更新任务的完成状态
export let asyncCheckTodo = (id, done) => {
  return async dispatch => {
    await instance.patch(`/todos/${id}`, {
      done: done
    });
    //更新状态
    dispatch({type: 'check_todo', payload: {id, done}})
  }
}